﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interop;
using System.Xml;
using VMuktiAPI;
using System.Text;
using System.Windows.Documents;
using System.Collections.Generic;
using System.Net;
namespace Weather.Presentation
{
    /// <summary>
    /// Interaction logic for UCWeather.xaml
    /// </summary>
    /// 
    public enum ModulePermissions
    {
        Add = 0,
        Edit = 1,
        Delete = 2,
        View = 3
    }

    public partial class UCWeather : UserControl,IDisposable
    {
        #region Fields

        WeatherService.GlobalWeather objWeatherService = new global::Weather.Presentation.WeatherService.GlobalWeather();
        
        public delegate void delLoadDock(string country,string city);
        public delLoadDock objdelLoadDock;
        
        private bool disposed = false;
        bool loading = true;
        static bool NetStatus = false;

        StringBuilder sb1 = CreateTressInfo();
      
        delegate void DelInvokeCmbChange();
        DelInvokeCmbChange objInvokeCmbChange;

        delegate void DelNetStatus(object a);
        DelNetStatus ObjDelNetstatus;

        public delegate void delfncNetStatus(object a);
        public delfncNetStatus objDelFunctionNetStatus;

        System.Timers.Timer objTimerNetStatus = new System.Timers.Timer();
        int getNetstatus = 0;
        int timercount = 0;
        string country, city = "";

        #endregion

        #region constructor
        public UCWeather(ModulePermissions[] MyPermissions)
        {
            try
            {
                InitializeComponent();


                #region Delegate Object
                objInvokeCmbChange = new DelInvokeCmbChange(funThreadCmb);
                objdelLoadDock = new delLoadDock(LoadDocK);
                ObjDelNetstatus = new DelNetStatus(FncNetStatus);
                objDelFunctionNetStatus = new delfncNetStatus(FncNetStatus);
                #endregion

                #region cheking netstatus
                System.Threading.Thread objthreadFncNetStatus = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(FunThreadNetStatus));
                objthreadFncNetStatus.Priority = System.Threading.ThreadPriority.AboveNormal;
                object a1 = new object();
                objthreadFncNetStatus.Start(a1);
                #endregion  

                #region event
                btnclick.Click += new RoutedEventHandler(btnclick_Click);
                btnCancle.Click += new RoutedEventHandler(btnCancle_Click);
                btnGet.Click += new RoutedEventHandler(btnGet_Click);
                cmbCountry.SelectionChanged += new SelectionChangedEventHandler(cmbCountry_SelectionChanged);
                objWeatherService.GetCitiesByCountryCompleted += new Weather.Presentation.WeatherService.GetCitiesByCountryCompletedEventHandler(objWeatherService_GetCitiesByCountryCompleted);
                objWeatherService.GetWeatherCompleted += new Weather.Presentation.WeatherService.GetWeatherCompletedEventHandler(objWeatherService_GetWeatherCompleted);
                #endregion

                fncCnvMain();
                
                #region loading
                try
                {
                    string strGetCookies = Application.GetCookie(BrowserInteropHelper.Source);
                    if (strGetCookies != null)
                    {
                        if (strGetCookies.Split(';').Length > 1)
                        {
                            if (strGetCookies.Split(';')[0].Trim().Split('=')[0].ToLower() == "country")
                            {
                               // this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Background, objdelLoadDock, strGetCookies.Split(';')[0].Trim().Split('=')[1], strGetCookies.Split(';')[1].Trim().Split('=')[1]);
                                country = strGetCookies.Split(';')[0].Trim().Split('=')[1];
                                city = strGetCookies.Split(';')[1].Trim().Split('=')[1];
                                System.Threading.Thread objThread = new System.Threading.Thread(new System.Threading.ThreadStart(FncThreadLoadDock));
                                objThread.IsBackground = true;
                                objThread.Priority = System.Threading.ThreadPriority.Normal;
                                objThread.Start();
                            }
                           
                        }

                    }
                    else
                    {
                        //this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Background, objdelLoadDock, "india", "Bombay / Santacruz");
                        country = "india";
                        city = "Bombay / Santacruz";
                        System.Threading.Thread objThread = new System.Threading.Thread(new System.Threading.ThreadStart(FncThreadLoadDock));
                        objThread.IsBackground = true;
                        objThread.Priority = System.Threading.ThreadPriority.Normal;
                        objThread.Start();
                    }
                }
                catch (Exception ex) // if cookies are not set then user ill get exception so defaultly we load weather for bombay
                {

                   // this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Background, objdelLoadDock, "india", "Bombay / Santacruz");
                    country = "india";
                    city = "Bombay / Santacruz";
                    System.Threading.Thread objThread = new System.Threading.Thread(new System.Threading.ThreadStart(FncThreadLoadDock));
                    objThread.IsBackground = true;
                    objThread.Priority = System.Threading.ThreadPriority.Normal;
                    objThread.Start();

                }
                #endregion

                #region loging
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("Weather Module:");
                sb.AppendLine("loading Weather module");
                sb.AppendLine(sb1.ToString());
                VMuktiAPI.ClsLogging.WriteToTresslog(sb);
                #endregion
            }
            catch (Exception exp)
            {
                exp.Data.Add("My Key", "UCWeather()--:--UCWeather.xaml.cs--:--" + exp.Message + " :--:--");
                ClsException.LogError(exp);
                ClsException.WriteToErrorLogFile(exp);
            }
                  
         }
        #endregion

        #region Webservice function

        void objWeatherService_GetWeatherCompleted(object sender, Weather.Presentation.WeatherService.GetWeatherCompletedEventArgs e)
        {
            try
            {
                bool error = false;

                #region retriving cookies
                string strGetCookies = "";
                try
                {
                     strGetCookies = Application.GetCookie(BrowserInteropHelper.Source);
                }
                catch (Exception ex)
                {
                    error = true;
                }
                #endregion

                string ss = e.Result;

                if (ss != "Data Not Found")
                {

                    #region setting country n state
                    string country = "";
                    string city = "";
                    if (loading)
                    {
                        if (strGetCookies.Length < 1)
                        {
                            country = "India";
                            city = "Bombay/Santacruz";

                        }
                        else
                        {
                            if (error == false)
                            {
                                country = strGetCookies.Split(';')[0].Trim().Split('=')[1];
                                city = strGetCookies.Split(';')[1].Trim().Split('=')[1];
                            }

                        }
                        loading = false;

                    }
                    else
                    {
                        country = ((ComboBoxItem)cmbCountry.SelectedItem).Content.ToString();
                        city = ((ComboBoxItem)cmbCity.SelectedItem).Content.ToString();
                    }
                    #endregion

                    #region parsing

                    if (ss != "Data Not Found")
                    {

                        XmlDocument doc = new XmlDocument();
                        doc.LoadXml(ss.ToString());
                        XmlNode nd = null;
                        nd = doc.SelectSingleNode("CurrentWeather");
                        if (nd.ChildNodes.Count == 0)
                            MessageBox.Show(string.Format("Data not available for {0}", country));
                        else
                        {
                            bool status = false;
                            foreach (XmlElement el in nd)
                            {
                                XmlNode xn = nd.SelectSingleNode("Temperature");


                                if (el.Name == "Temperature")
                                {
                                    string s = el.InnerText;
                                    lblValue.Content = s;
                                    lblName.Visibility = Visibility.Visible;
                                    lblName.Content = city.Split('/')[0];
                                    expMenu.Items.Add(el.Name + "=" + el.InnerText.ToString());
                                    status = true;
                                }

                                else if (el.Name != "Status" && el.Name != "Time" && el.Name != "Temperature" && el.Name != "Location")
                                {
                                    expMenu.Items.Add(el.Name + "=" + el.InnerText.ToString());
                                }
                            }
                            if (status == false)
                            {
                                lblValue.Content = "";
                                lblName.Visibility = Visibility.Visible;
                                lblName.Content = "Not Available";
                            }
                        }


                    }
                    else
                    {
                        lblName.Visibility = Visibility.Visible;
                        lblName.Content = "Not Available";
                        lblValue.Content = "";
                    }
                    #endregion
                }
                else
                {
                    cnvlbl.Visibility = Visibility.Collapsed;
                    cnvMain.Visibility = Visibility.Visible;
                    lblName.Content = "Not Available";
                }
            }
            catch (Exception exp)
            {
                exp.Data.Add("My Key", "objWeatherService_GetWeatherCompleted()--:--UCWeather.xaml.cs--:--" + exp.Message + " :--:--");
                ClsException.LogError(exp);
                ClsException.WriteToErrorLogFile(exp);
            }
        }

        void objWeatherService_GetCitiesByCountryCompleted(object sender, Weather.Presentation.WeatherService.GetCitiesByCountryCompletedEventArgs e)
        {
            try
            {
                string ss1 = e.Result;
                if (ss1 != "Data Not Found")
                {
                    cmbCity.Items.Clear();

                    #region xmlDoc

                    XmlDocument doc = new XmlDocument();
                    doc.LoadXml(ss1.ToString());
                    XmlNode nd = null;
                    nd = doc.SelectSingleNode("NewDataSet");
                    if (nd.ChildNodes.Count == 0)
                        MessageBox.Show(string.Format("Data not available for {0}", ((ComboBoxItem)cmbCountry.SelectedItem).Content.ToString()));
                    else
                    {
                        foreach (XmlElement el in nd)
                        {
                            if (el.Name == "Table")
                            {
                                if (el.HasChildNodes == true)
                                {
                                    foreach (XmlNode atr in el)
                                    {
                                        if (atr.Name == "City")
                                        {
                                            cmbCity.Items.Add(new ComboBoxItem());
                                            ((ComboBoxItem)cmbCity.Items[cmbCity.Items.Count - 1]).Content = atr.InnerText;
                                        }
                                    }
                                }
                            }
                            else
                            {
                                MessageBox.Show("Data Not Available try another country");
                            }
                        }
                    }

                    #endregion
                }
                else
                {
                    cnvlbl.Visibility = Visibility.Collapsed;
                    cnvMain.Visibility = Visibility.Visible;
                    lblName.Content = "Not Available";
                }
            }
            catch (Exception exp)
            {
                exp.Data.Add("My Key", "objWeatherService_GetCitiesByCountryCompleted()--:--UCWeather.xaml.cs--:--" + exp.Message + " :--:--");
                ClsException.LogError(exp);
                ClsException.WriteToErrorLogFile(exp);
            }
        }

        #endregion

        #region Loaddock

        public void FncThreadLoadDock()
        {
            try
            {
                objTimerNetStatus.Interval = 5000;
                objTimerNetStatus.Elapsed += new System.Timers.ElapsedEventHandler(objTimerNetStatus_Elapsed);
                objTimerNetStatus.Start();
            }
            catch (Exception exp)
            {
                exp.Data.Add("My Key", "FncThreadLoadDock()--:--UCWeather.xaml.cs--:--" + exp.Message + " :--:--");
                ClsException.LogError(exp);
                ClsException.WriteToErrorLogFile(exp);
            }
            
        }

        public void LoadDocK(string country,string city)
        {
            
            try
            {
                //System.Threading.Thread objThread = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(FncNetStatus));
                //objThread.Priority = System.Threading.ThreadPriority.Highest;
                //objThread.IsBackground = true;
                //objThread.Start();
                //this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Background, ObjDelNetstatus);
                //object a = null;
                //FncNetStatus(a);

                if (NetStatus==true)
                {
                    objWeatherService.GetWeatherAsync(city, country);
                   
                }
                else
                {
                        lblName.Visibility = Visibility.Visible;
                        lblName.Content = "Net Is not Available";
                        lblValue.Content = "";
                }
            }
            catch (Exception exp)
            {
                exp.Data.Add("My Key", "LoadDocK()--:--UCWeather.xaml.cs--:--" + exp.Message + " :--:--");
                ClsException.LogError(exp);
                ClsException.WriteToErrorLogFile(exp);
            }
        }

        void btnGet_Click(object sender, RoutedEventArgs e)
        {
            try
            {

                lblValue.Content = "";
                expMenu.Items.Clear();
                lblName.Content = "Loading...";

                //this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Background, objdelLoadDock, ((ComboBoxItem)cmbCountry.SelectedItem).Content.ToString(), ((ComboBoxItem)cmbCity.SelectedItem).Content.ToString());
                country = ((ComboBoxItem)cmbCountry.SelectedItem).Content.ToString();
                city = ((ComboBoxItem)cmbCity.SelectedItem).Content.ToString();
                System.Threading.Thread ObjThread1 = new System.Threading.Thread(new System.Threading.ThreadStart(FncThreadLoadDock));
                ObjThread1.IsBackground = true;
                ObjThread1.Start();


                if (chkDefault.IsChecked == true)
                {
                    Application.SetCookie(BrowserInteropHelper.Source, "Country=" + ((ComboBoxItem)cmbCountry.SelectedItem).Content.ToString() + "; expires=Sat, 24-Dec-2999 16:00:00 GMT");
                    Application.SetCookie(BrowserInteropHelper.Source, "City=" + ((ComboBoxItem)cmbCity.SelectedItem).Content.ToString() + "; expires=Sat, 24-Dec-2999 16:00:00 GMT");

                }

                fncCnvMain();

                #region logging
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("weather module: user request to get current weather of ");
                sb.AppendLine("country :" + ((ComboBoxItem)cmbCountry.SelectedItem).Content.ToString() + "state:" + ((ComboBoxItem)cmbCity.SelectedItem).Content.ToString());
                sb.AppendLine(sb1.ToString());
                VMuktiAPI.ClsLogging.WriteToTresslog(sb);
                #endregion

            }
            catch (Exception exp)
            {
                MessageBox.Show("U must have to select city and state");
                exp.Data.Add("My Key", "btnGet_Click()--:--UCWeather.xaml.cs--:--" + exp.Message + " :--:--");
                ClsException.LogError(exp);
                ClsException.WriteToErrorLogFile(exp);
            }

        }

        #endregion

        #region NetStatus

        void FunThreadNetStatus(object temp)
        {
            try
            {
                this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Background, objDelFunctionNetStatus, temp);
            }
            catch (Exception exp)
            {
                exp.Data.Add("My Key", "FunThreadNetStatus()--:--UCWeather.xaml.cs--:--" + exp.Message + " :--:--");
                ClsException.LogError(exp);
                ClsException.WriteToErrorLogFile(exp);
            }
        }
        
        public void  FncNetStatus(object temp)
        {

            try
            {
                HttpWebRequest req;
                HttpWebResponse resp;
                try
                {
                    req = (HttpWebRequest)WebRequest.Create("http://www.google.com");
                    resp = (HttpWebResponse)req.GetResponse();

                    if (resp.StatusCode.ToString().Equals("OK"))
                    {
                        NetStatus = true;

                    }
                    else
                    {
                        NetStatus = false;
                        getNetstatus = 1;
                    }
                }
                catch (Exception exc)
                {
                    //Console.WriteLine("its not connected.");
                    NetStatus = false;
                    getNetstatus = 1;
                }
            }
            catch(Exception exp)
            {
                exp.Data.Add("My Key", "FncNetStatus()--:--UCWeather.xaml.cs--:--" + exp.Message + " :--:--");
                ClsException.LogError(exp);
                ClsException.WriteToErrorLogFile(exp);
            }

        }

        void objTimerNetStatus_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {

            try
            {
                if (loading)
                {
                    if (getNetstatus == 1)
                    {
                        this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Background, objdelLoadDock, country, city);
                        objTimerNetStatus.Stop();

                        if (NetStatus == false)
                        {
                            timercount = 3;
                        }
                    }
                    timercount++;
                    if (timercount > 1)
                    {
                        objTimerNetStatus.Stop();
                        this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Background, objdelLoadDock, country, city);
                        //this time dispature will tell that net is not availabe
                    }
                }
                else
                {
                    this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Background, objdelLoadDock, country, city);
                    objTimerNetStatus.Stop();
                }
            }
            catch (Exception exp)
            {
                exp.Data.Add("My Key", "objTimerNetStatus_Elapsed()--:--ctlOurNews.xaml.cs--:--" + exp.Message + " :--:--");
                ClsException.LogError(exp);
                ClsException.WriteToErrorLogFile(exp);
            }
        }

        #endregion

        #region combo Selection chang

        void cmbCountry_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                loading = false;
                if (NetStatus == true)
                {
                    this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Background, objInvokeCmbChange);
                    cmbCity.Items.Clear();
                    cmbCity.Items.Add("Loading...");
                }
                else
                {
                    cnvlbl.Visibility = Visibility.Collapsed;
                    cnvMain.Visibility = Visibility.Visible;
                    lblName.Content = "Net Not Available";
                }
            }
            catch (Exception exp)
            {
                exp.Data.Add("My Key", "cmbCountry_SelectionChanged()--:--UCWeather.xaml.cs--:--" + exp.Message + " :--:--");
                ClsException.LogError(exp);
                ClsException.WriteToErrorLogFile(exp);
            }
        }

        void fncInvokeCmbChange()
        {
            try
            {
                this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, objInvokeCmbChange);
            }
            catch (Exception exp)
            {
                exp.Data.Add("My Key", "fncInvokeCmbChange()--:--UCWeather.xaml.cs--:--" + exp.Message + " :--:--");
                ClsException.LogError(exp);
                ClsException.WriteToErrorLogFile(exp);
            }
        }

        void funThreadCmb()
        {
            try
            {
                string strcountry = ((ComboBoxItem)cmbCountry.SelectedItem).Content.ToString();
                cnvlbl.Visibility = Visibility.Visible;
                if (NetStatus==true)
                {
                    objWeatherService.GetCitiesByCountryAsync(strcountry);
                }
                else
                {
                    MessageBox.Show("Internet is not accesible please try after sometime");
                }

                StringBuilder sb = new StringBuilder();
                sb.AppendLine("weather module: country is selected by user.");
                sb.AppendLine("Country is :" + strcountry);
                sb.AppendLine(sb1.ToString());
                VMuktiAPI.ClsLogging.WriteToTresslog(sb);

            }
            catch (Exception exp)
            {
                exp.Data.Add("My Key", "funThreadCmb()--:--UCWeather.xaml.cs--:--" + exp.Message + " :--:--");
                ClsException.LogError(exp);
                ClsException.WriteToErrorLogFile(exp);
            }
        }

        #endregion

        #region tempFunction

        void btnCancle_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                fncCnvMain();
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("Weather module: cancel button is clicked by user");
                sb.AppendLine(sb1.ToString());
                VMuktiAPI.ClsLogging.WriteToTresslog(sb);
            }
            catch (Exception exp)
            {
                exp.Data.Add("My Key", "btnCancle_Click()--:--UCWeather.xaml.cs--:--" + exp.Message + " :--:--");
                ClsException.LogError(exp);
                ClsException.WriteToErrorLogFile(exp);
            }
        }

        void btnclick_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                fncCnvlbl();
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("weather module: setting button is clicked to configur city and state.");
                sb.AppendLine(sb1.ToString());
                VMuktiAPI.ClsLogging.WriteToTresslog(sb);
            }
            catch (Exception exp)
            {
                exp.Data.Add("My Key", "btnclick_Click()--:--UCWeather.xaml.cs--:--" + exp.Message + " :--:--");
                ClsException.LogError(exp);
                ClsException.WriteToErrorLogFile(exp);
            }
        }
        
        void fncCnvlbl()
        {
            try
            {
                cnvMain.Visibility = Visibility.Collapsed;
                cnvlbl.Visibility = Visibility.Visible;
            }

            catch (Exception exp)
            {
                exp.Data.Add("My Key", "fncCnvlbl()--:--UCWeather.xaml.cs--:--" + exp.Message + " :--:--");
                ClsException.LogError(exp);
                ClsException.WriteToErrorLogFile(exp);
            }
        }

        void fncCnvMain()
        {
            try
            {
                cnvMain.Visibility = Visibility.Visible;
                cnvlbl.Visibility = Visibility.Collapsed;
            }

            catch (Exception exp)
            {
                exp.Data.Add("My Key", "fncCnvMain()--:--UCWeather.xaml.cs--:--" + exp.Message + " :--:--");
                ClsException.LogError(exp);
                ClsException.WriteToErrorLogFile(exp);
            }
        }

        public void ClosePod()
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("weather module: module is closed by user ");
            sb.AppendLine(sb1.ToString());
            VMuktiAPI.ClsLogging.WriteToTresslog(sb);
            try
            {
                this.Dispose();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }

            catch (Exception exp)
            {
                exp.Data.Add("My Key", "ClosePod()--:--UCWeather.xaml.cs--:--" + exp.Message + " :--:--");
                ClsException.LogError(exp);
                ClsException.WriteToErrorLogFile(exp);
            }
        }

        #region destructor

        public void Dispose()
        {
            //VMuktiAPI.ClsException.WriteToErrorLogFile(new Exception("-------amit--------Dispposed is called in simple dispose"));
            Dispose(true);
            //GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    objdelLoadDock = null;
                    LayoutRoot = null;
                    cnvlbl = null;
                    cnvMain = null;
                    cmbCity = null;
                    objInvokeCmbChange=null;
                    ObjDelNetstatus = null;
                    objDelFunctionNetStatus = null;
                    objTimerNetStatus.Dispose();
                    getNetstatus = 0;
                    timercount = 0;
                    country = null;
                    city = null;
                                        
                }
                this.objWeatherService.Dispose();
            }
            disposed = true;
        }

        ~UCWeather()
        {
            this.Dispose();
            System.GC.Collect();
           // System.GC.WaitForPendingFinalizers();
        }

        #endregion

        #region logging function

        public static StringBuilder CreateTressInfo()
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("User Is : " + VMuktiAPI.VMuktiInfo.CurrentPeer.DisplayName);
                sb.AppendLine();
                sb.Append("Peer Type is : " + VMuktiAPI.VMuktiInfo.CurrentPeer.CurrPeerType.ToString());
                sb.AppendLine();
                sb.Append("User's SuperNode is : " + VMuktiAPI.VMuktiInfo.CurrentPeer.SuperNodeIP);
                sb.AppendLine();
                sb.Append("User's Machine Ip Address : " + VMuktiAPI.GetIPAddress.ClsGetIP4Address.GetIP4Address());
                sb.AppendLine("--------------------------------------------------------------------------------------");
                return sb;
            }
            catch (Exception exp)
            {
                exp.Data.Add("My Key", "CreateTressInfo()--:--UCWeather.xaml.cs--:--" + exp.Message + " :--:--");
                ClsException.LogError(exp);
                ClsException.WriteToErrorLogFile(exp);
                return null;
            }
        }

        #endregion

        #endregion

    }
}
